package com.mrx.compose.weather.api

import com.google.gson.Gson
import com.mrx.compose.weather.api.annotations.Api
import okhttp3.OkHttpClient
import org.slf4j.LoggerFactory
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object ApiHelper {

    private val logger = LoggerFactory.getLogger(this::class.java)

    private val client = OkHttpClient.Builder()
        .addNetworkInterceptor {
            val request = it.request()
            logger.debug("正在请求: {}", request.url)
            it.proceed(request)
        }.build()

    val gson = Gson()

    private val retrofit: Retrofit.Builder = Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create(gson))
        .client(client)

    private val apiCache = hashMapOf<Class<*>, Any>()

    fun <T : Any> getAPI(clazz: Class<T>): T {
        val apiAnnotationClass = Api::class.java
        check(clazz.isAnnotationPresent(apiAnnotationClass)) { "api 接口必须使用 ${apiAnnotationClass.name} 注解修饰" }
        val baseURL = clazz.getAnnotation(apiAnnotationClass).baseURL
        check(baseURL.isNotEmpty()) { "BaseUrl 不能为空" }
        val apiInstance = retrofit.baseUrl(baseURL).build().create(clazz)
        return clazz.cast(apiCache.computeIfAbsent(clazz) { apiInstance })
    }

    inline fun <reified T : Any> getAPI(): T {
        return getAPI(T::class.java)
    }

}
